// api/handlers/auth_handler.go
package handlers

import (
	"mygin/internal/services"
	"mygin/pkg/response"
	"net/http"

	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

type AuthHandler struct {
	authService services.AuthService
}

func NewAuthHandler(svc services.AuthService) *AuthHandler {
	return &AuthHandler{authService: svc}
}

// Login 用户登录
// @Summary 用户登录
// @Description 用户登录
// @Tags 用户管理
// @Accept json
// @Produce json
// @Param username path string true "用户名"
// @Param password path string true "密码"
// @Success 200 {object} models.User
// @Failure 400 {object} response.ErrorResponse "无效的用户名"
// @Failure 404 {object} response.ErrorResponse "用户不存在"
// @Router /api/v1/auth/login [post]
func (h *AuthHandler) Login(c *gin.Context) {
	var creds struct {
		Username string `json:"username"`
		Password string `json:"password"`
	}

	if err := c.ShouldBindJSON(&creds); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数格式错误"})
		return
	}

	// 验证用户凭证逻辑...
	// 1. 查询用户
	user, err := h.authService.FindByUsername(creds.Username)
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "用户不存在"})
		return
	}

	// 2. 使用 bcrypt 验证密码
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(creds.Password)); err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "密码错误"})
		return
	}

	//生成令牌
	accessToken, refreshToken, err := h.authService.GenerateTokens(user)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "token generation failed"})
		return
	}

	userMap := gin.H{
		"id":       user.ID,
		"username": user.Username,
		"tel":      user.Tel,
		// 其他字段...
		"tokens": gin.H{ // 新增 tokens 字段
			"access_token":  accessToken,
			"refresh_token": refreshToken,
		},
	}
	c.JSON(http.StatusOK, response.Success("ok", userMap))
}

// Register 处理用户注册请求
func (h *AuthHandler) Register(c *gin.Context) {
	var registration struct {
		Username string `json:"username" binding:"required,min=3,max=20"`
		Password string `json:"password" binding:"required,min=6"`
		Tel      string `json:"tel" binding:"required,len=11,numeric"`
		// 可以添加更多注册字段，如姓名、手机号等
	}

	if err := c.ShouldBindJSON(&registration); err != nil {
		c.JSON(http.StatusOK, response.Fail(400, err.Error()))
		return
	}

	// 检查用户名是否已存在
	existingUser, err := h.authService.FindByUsername(registration.Username)
	if err == nil && existingUser != nil {
		c.JSON(http.StatusConflict, gin.H{"error": "用户名已被占用"})
		return
	}

	// 检查手机号是否已注册
	existingTelUser, err := h.authService.FindByTel(registration.Tel)
	if err == nil && existingTelUser != nil {
		c.JSON(http.StatusConflict, gin.H{"error": "手机号已被注册"})
		return
	}

	// 创建用户 (实际项目中密码应该加密存储)
	user, err := h.authService.CreateUser(
		registration.Username,
		registration.Password, // 实际项目中这里应该是加密后的密码
		registration.Tel,
	)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "注册失败"})
		return
	}

	// 注册成功后直接登录，返回token
	accessToken, refreshToken, err := h.authService.GenerateTokens(user)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "token generation failed"})
		return
	}
	userMap := gin.H{
		"id":       user.ID,
		"username": user.Username,
		"tel":      user.Tel,
		// 其他字段...
		"tokens": gin.H{ // 新增 tokens 字段
			"access_token":  accessToken,
			"refresh_token": refreshToken,
		},
	}
	c.JSON(http.StatusOK, response.Success("ok", userMap))
}

func (h *AuthHandler) RefreshToken(c *gin.Context) {
	var request struct {
		RefreshToken string `json:"refresh_token" binding:"required"`
	}

	if err := c.ShouldBindJSON(&request); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
		return
	}

	accessToken, refreshToken, err := h.authService.RefreshTokens(request.RefreshToken)
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"access_token":  accessToken,
		"refresh_token": refreshToken,
	})
}
